package com.smartlifev30.baiwei.activity;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smartlifev30.R;
import com.smartlifev30.baiwei.adapter.ZoneFragmentAdapter;
import com.smartlifev30.baiwei.fragment.ZoneTypeFragment;
import com.smartlifev30.baiwei.view.Indicator;

import java.lang.reflect.Field;
import java.util.ArrayList;


/**
 * @author tys
 */
public class ZoneActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;

    /**
     * 目前仅支持fixed模式
     * table指示器(小三角形)
     */
    private Indicator mIndicator;

    /**
     * TableLayout中顶层table容器,反射获取(用于计算滑动的距离)
     */
    private LinearLayout mTabStrip;

    /**
     * table指示器动画(点击选择table时使用)
     */
    private ValueAnimator mIndicatorAnimator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zone);
        initView();
    }

    private void initView() {
        mIndicator = findViewById(R.id.zone_pointer);
        tabLayout = findViewById(R.id.zone_tab_layout);
        viewPager = findViewById(R.id.zone_view_pager);
        tabLayout.setupWithViewPager(viewPager);
        ArrayList<Fragment> data = new ArrayList<>();

        data.add(ZoneTypeFragment.newInstance("在家", "2"));
        data.add(ZoneTypeFragment.newInstance("外出", "2"));
        data.add(ZoneTypeFragment.newInstance("睡眠", "2"));
        data.add(ZoneTypeFragment.newInstance("一键撤防", "2"));

        viewPager.setAdapter(new ZoneFragmentAdapter(getSupportFragmentManager(), data));
        viewPager.addOnPageChangeListener(new ViewPagerChangeListen());
        for (int i = 0, count = tabLayout.getTabCount(); i < count; i++) {
            TabLayout.Tab tabAt = tabLayout.getTabAt(i);
            if (tabAt != null) {
                switch (i) {
                    //在家
                    case 0:
                        tabAt.setCustomView(R.layout.zone_at_home_item);
                        break;
                    //外出
                    case 1:
                        tabAt.setCustomView(R.layout.zone_out_home_item);
                        break;
                    //睡眠
                    case 2:
                        tabAt.setCustomView(R.layout.zone_sleep_item);
                        break;
                    //一键撤防
                    case 3:
                        tabAt.setCustomView(R.layout.zone_clean_item);
                        break;
                    default:
                }
            }
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                setSelectedTabUi(tab.getCustomView(), tab.getPosition(), true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                super.onTabUnselected(tab);
                setSelectedTabUi(tab.getCustomView(), tab.getPosition(), false);
            }
        });
    }

    private void setSelectedTabUi(View customView, int position, boolean isSelected) {
        TextView tv = null;
        switch (position) {
            case 0:
                tv = customView.findViewById(R.id.zone_at_home_table_tv);
                break;
            case 1:
                tv = customView.findViewById(R.id.zone_out_home_table_tv);
                break;
            case 2:
                tv = customView.findViewById(R.id.zone_sleep_table_tv);
                break;
            case 3:
                tv = customView.findViewById(R.id.zone_clean_table_tv);
                break;
            default:
        }
        if (tv != null) {
            if (isSelected) {
                tv.setTextColor(getResources().getColor(R.color.tabTextSelected));
            } else {
                tv.setTextColor(getResources().getColor(R.color.tabTextSelectedNor));
            }
        }
    }

    public void titleBack(View view) {
        onBackPressed();
    }

    private @Nullable
    LinearLayout getTabStrip(TabLayout tabLayout) {
        if (mTabStrip != null) {
            return mTabStrip;
        }
        try {
            Field mTabStrip = TabLayout.class.getDeclaredField("mTabStrip");
            mTabStrip.setAccessible(true);
            this.mTabStrip = (LinearLayout) mTabStrip.get(tabLayout);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return mTabStrip;
    }

    private void updateIndicatorPosition(LinearLayout tabStrip, int position, float positionOffset) {
        if (tabStrip == null) {
            return;
        }
        final View selectedTitle = tabStrip.getChildAt(position);
        int left = -1, right = -1;
        if (selectedTitle != null && selectedTitle.getWidth() > 0) {
            left = selectedTitle.getLeft();
            right = selectedTitle.getRight();
            if (positionOffset > 0f && position < tabStrip.getChildCount() - 1) {
                View nextTitle = tabStrip.getChildAt(position + 1);
                left = (int) (positionOffset * nextTitle.getLeft() +
                        (1.0f - positionOffset) * left);
                right = (int) (positionOffset * nextTitle.getRight() +
                        (1.0f - positionOffset) * right);
            }
        }
        mIndicator.smoothToX((right - left) / 2 + left);
    }

    private class ViewPagerChangeListen implements ViewPager.OnPageChangeListener {
        private int mPreviousScrollState;
        private int mScrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            final boolean updateIndicator = !(mScrollState == ViewPager.SCROLL_STATE_SETTLING
                    && mPreviousScrollState == ViewPager.SCROLL_STATE_IDLE);
            //不是点击
            if (updateIndicator) {
                LinearLayout tabStrip = getTabStrip(tabLayout);
                updateIndicatorPosition(tabStrip, position, positionOffset);
            }
        }

        @Override
        public void onPageSelected(int position) {
            final boolean updateIndicator = mScrollState == ViewPager.SCROLL_STATE_IDLE
                    || (mScrollState == ViewPager.SCROLL_STATE_SETTLING
                    && mPreviousScrollState == ViewPager.SCROLL_STATE_IDLE);
            //代码设置位置 或 点击
            if (updateIndicator) {
                if (mIndicatorAnimator != null && mIndicatorAnimator.isRunning()) {
                    mIndicatorAnimator.cancel();
                }
                final View targetView = mTabStrip.getChildAt(position);
                final int targetLeft = targetView.getLeft();
                final int targetRight = targetView.getRight();
                ValueAnimator animator = mIndicatorAnimator = new ValueAnimator();
                animator.setInterpolator(new FastOutSlowInInterpolator());
                animator.setDuration(300);
                animator.setIntValues(targetLeft, (targetRight - targetLeft) / 2 + targetLeft);
                animator.addUpdateListener(animator1 -> {
                    final int fraction = (int) animator1.getAnimatedValue();
                    mIndicator.smoothToX(fraction);
                });
                animator.start();
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mPreviousScrollState = mScrollState;
            mScrollState = state;
        }
    }
}
